package com.chucang.shucang.common.security.utils;

import cn.hutool.core.text.CharSequenceUtil;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.security.entity.ShuCangUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/18 1:36
 * @description security上下文操作工具
 */
@UtilityClass
public class SecurityUtil {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public ShuCangUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof ShuCangUser) {
            return (ShuCangUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public ShuCangUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Long> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Long> roleIds = new ArrayList<>();
        authorities.stream().filter(granted -> CharSequenceUtil
                        .startWith(granted.getAuthority(), SecurityConstant.ROLE))
                .forEach(granted -> {
                    String id = CharSequenceUtil
                            .removePrefix(granted.getAuthority(), SecurityConstant.ROLE);
                    roleIds.add(Long.parseLong(id));
                });
        return roleIds;
    }
}
